<template>
	<view class="page">
		<view class="navbar">{{ current+1 }}/{{ displaySwiperList.length }}</view>
		<view class="content" @touchstart="touchstart" @touchend="touchend" >
			<swiper class="swiper" :autoplay="autoPlay" :interval="(value2+valueCount) * 1000" :circular="circular"
				@change="swiperChange" swiperDuration="250" :current="swiperIndex">
				<swiper-item class="swiper-list" v-for="(val, index) in swiperLength" :key="index">
					<view class="swiper-item" v-if="computedIndex(index)">
						<view class="collect" @click="collectHandle(index)">
							<image v-if="computedIndex(index).favorite" src="/static/star.png" mode=""></image>
							<image v-else src="/static/star1.png" mode=""></image>
						</view>
						<view class="word">{{ computedIndex(index).name }}</view>
						<!-- <view class="spring">/ˈmeʒə(r)/ </view> -->
						<view style="text-align: center;">
							<wordphonetic style="display: inline-block;" :isSpell="false" :data="computedIndex(index)"></wordphonetic>
						</view>
						
						<wordexplain :data="computedIndex(index).explain" :parentData="computedIndex(index)"></wordexplain>
						
						<!-- <view class="mean" v-if="computedIndex(index) && computedIndex(index).explain">
							<view v-for="(q,qindex) in computedIndex(index).explain" :key="qindex">
								<view v-if="q" class="t"  >{{ q.wordSex }} {{ q.chinExplain }}
								</view>
							</view>
						</view> -->
						<view class="memory" v-if="computedIndex(index).mnemonic && computedIndex(index).mnemonic.length > 0">
							<view class="con">
								<view v-for="(val2, i) in computedIndex(index).mnemonic" :key="i">
                  {{val2.mnemonicMethodName}}{{ val2.name }}
                </view>
							</view>
						</view>
						<view class="spell">
              <!--
              <u-icon @click="spell(computedIndex(index))" name="volume" size="24"
								color="#5480F8"></u-icon>
							-->
              <image
                src="https://sqh-1311961031.cos.ap-nanjing.myqcloud.com/%E7%BB%84%2057%402x_1716792586903.png"
                style="width: 48rpx; height: 48rpx;"
                @click="spell(computedIndex(index))"
              ></image>
            </view>
					</view>
				</swiper-item>
			</swiper>
		</view>
		<view class="page-btn d_flex_b">
			<view class="set" @click="openPop">
				<image src="/static/set.png" mode=""></image>
			</view>
			<view class="btn" v-if="!isStart" @click="start">播放</view>
			<view class="btn stop" v-else @click="stop">暂停</view>
		</view>
		<uni-popup ref="popup" type="bottom" :safe-area="false" @maskClick="closePop">
			<view class="pop-box">
				<view class="tit">播放设置</view>
				<view class="picker-box d_flex_b">
					<view class="box flex1">
					<!-- 	<picker-view :indicator-style="indicatorStyle" :value="value1" @change="bindChange1"
							class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item, index) in list1" :key="index">循环{{ item }}次</view>
							</picker-view-column>
						</picker-view> -->
						<picker-view :indicator-style="indicatorStyle" :value="valueCount" @change="bindChange1"
							class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item, index) in list1" :key="index">循环{{ item }}次</view>
							</picker-view-column>
						</picker-view>
					</view>
					<view class="box flex1">
						<picker-view :indicator-style="indicatorStyle" :value="value2" @change="bindChange2"
							class="picker-view">
							<picker-view-column>
								<view class="item" v-for="(item, index) in list2" :key="index">间隔{{ item }}秒</view>
							</picker-view-column>
						</picker-view>
					</view>
				</view>
				<view class="save">
					<view class="btn" @click="saveSet">保存设置</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	let wxAudio = null;
	export default {
		data() {
			return {
				thouchTime:null,
				getTimes:null,
				wordBookId:'',
				int: 0,
				innerAudioContext: '', //音频文件
				langType: 'en', //口语类型
				indicatorStyle: `height: 45px;`,
				list1: [1, 2, 3], //循环次数数组
				list2: [3, 5, 10], //间隔秒数数组
				value1: 1, //循环次数
				valueCount: 1, //循环次数
				num: 0, //当前已循环次数
				count: 1,
				value2: 3, //间隔秒数
				type: '',
				isStart: true, //快闪开关
				position: '', //当前位置（偏移量）
				offset: '', //偏移量
				total: '', //总数
				limit: 10, //每页请求单词数
				originList: [], //单词数组
				autoPlay: false, //是否自动播放
				circular: true, //是否无限循环
				current: 0, // 当前展示数据在列表中的索引值
				displaySwiperList: [], // swiper需要的数据
				displayIndex: 0, // 用于显示swiper的真正的下标数值只有：0，1，2。
				originIndex: 0, // 记录源数据的下标
				swiperIndex:5,
				swiperLength:10,//定10个item ，保证性能
			};
		},
		onLoad(e) {
			wxAudio = wx.createInnerAudioContext({});
			this.langType = uni.getStorageSync('langType') || 'en';
			// this.value1 = uni.getStorageSync('count') || 1;
			// this.value1 =  1;
			this.valueCount = uni.getStorageSync('count') || 1;
			this.value2 = uni.getStorageSync('cTime') || 3;
			this.wordBookId =(uni.getStorageSync('curBook') || {}).id;
			let position = Number(e.position);
			if(position.toString()==="NaN"){
				position=0;
			}
			this.position = position; //获取偏移量
			this.type = e.type;
			this.total = e.total;
			this.autoPlay = true;
			this.originIndex = position;
			this.current = position;
			this.displaySwiperList.length=e.total;
			let offset = position-5<0?0:position-5
			this.getList({
				offset:offset,
				limit:10
			},()=>{
				this.initSwiperData(this.displaySwiperList[this.current]);
				this.getSource(this.current-1);
				this.getSource(this.current+1)
			});
			if(this.displaySwiperList.length>10){
				if(offset===0){
					this.getList({
						offset:this.displaySwiperList.length-10,
						limit:10
					});
				}else if(offset===this.displaySwiperList.length-1){
					this.getList({
						offset:0,
						limit:10
					});
				}
			}
		},
		computed: {

		},
		methods: {
			touchstart(e){
				
				//console.log("开始")
				this.autoPlay=false;
			},
			touchend(e){
				if(this.thouchTime){
					clearTimeout(this.thouchTime);
				}
				this.thouchTime = setTimeout(()=>{
					this.autoPlay=true;
					this.thouchTime=null;
				},1000);
				//console.log("结束")	
				
			},
			computedIndex(index){
				let currentIndex = this.swiperIndex;//显示的序号
				let current = this.current;//数据的序号
				if(index===currentIndex){
					return this.displaySwiperList[current];
				}else{
					let tranIndex = current+(index-currentIndex);
					if(tranIndex>this.displaySwiperList.length-1){
						return this.displaySwiperList[tranIndex - this.displaySwiperList.length-1];
					}else if(tranIndex<0){
						return this.displaySwiperList[this.displaySwiperList.length-1 + tranIndex]
					}
					return this.displaySwiperList[tranIndex];
				}
			},
			getList(params,callback) {
				this.$http.get1('api/client/word/quickShotWord', {
					type: this.type,
					...params,
				}).then(res => {
					if (res.code == 200) {
						
						res.data.forEach((val,index) => {
							
							try{
								val.explain = JSON.parse(val.wordExplain);
							}catch(e){
								val.explain=[];
							}
							if(!Array.isArray(val.explain)){
								val.explain=[]
							}
							let pindex = params.offset+index;
							if(pindex<this.displaySwiperList.length){
								this.displaySwiperList.splice(pindex,1,val);
							}
						});
						callback && callback();
					}
				});
			},
			initSwiperData(item) {
				wxAudio.stop();
				// this.spell(item);
				// 循环读2遍， 
				let valueCount=this.valueCount
				this.spellCount(item,valueCount)
			},
			async spellCount(item,valueCount=1) {
				for (let index = 0; index < valueCount; index++) {
					await this.spell(item);
				}
			},
			swiperChange(event) {
				if(this.getTimes){
					return;
				}
				this.getTimes=setTimeout(()=>{
					this.getTimes=null;
				},1000);
				const {
					current
				} = event.detail;
				let type=""
				if(this.swiperIndex===9&&current===0){
					type="right"
					this.current++;
				}else if(this.swiperIndex===0&&current===9){
					type="left"
					this.current--;
				}else if(this.swiperIndex<current){
					type="right"
					this.current++;
				}else if(this.swiperIndex>current){
					type="left"
					this.current--;
				}
				if(this.current>=this.displaySwiperList.length){
					this.current=0;
				}else if(this.current<0){
					this.current = this.displaySwiperList.length-1;
				}
				//console.log(current,this.current,this.swiperIndex,type);
				this.swiperIndex=current;
				
				if(this.circular){
					if(this.current+3>=this.displaySwiperList.length&&this.displaySwiperList[0]===undefined){
						this.getList({
							offset:0,
							limit:10
						});
					}
					if(this.current-3<=0&&this.displaySwiperList[this.displaySwiperList.length-1<0?0:this.displaySwiperList.length-1]===undefined){
						this.getList({
							offset:this.displaySwiperList.length-10<0?0:this.displaySwiperList.length-10,
							limit:10
						});
					}
				}
				//左滑
				if(type==="left"){
					let currentscope = this.current-2;
					if(this.current-2<0){
						currentscope=0;
					}
					if(this.displaySwiperList[currentscope]===undefined){
						this.getList({
							offset:currentscope,
							limit:2
						});
					}
				}else{
					//右划
					let currentscope = this.current+2;
					if(currentscope>=this.displaySwiperList.length){
						currentscope=this.displaySwiperList.length-1
					}
					if(this.current===this.displaySwiperList.length-1){
						this.count++;
					}
					if(this.displaySwiperList[currentscope]===undefined){
						this.getList({
							offset:currentscope,
							limit:10
						});
					}
				}
				this.initSwiperData(this.displaySwiperList[this.current]);
				this.getSource(this.current-1);
				this.getSource(this.current+1)
				if(this.count>this.value1){
					this.autoPlay = false;
					this.isStart = false;
				}
			},
			start() {
				this.isStart = true;
				this.count = 1;
				this.autoPlay = true;
			},
			stop() {
				this.isStart = false;
				this.autoPlay = false;
			},
			collectHandle(index) {
				
				let val = this.computedIndex(index);
				this.$http
					.get1('/api/client/word/favoritesUpdate', {
						wordBookId: this.wordBookId,
						wordId: val.id,
						action: val.favorite ? '1' : '0'
					})
					.then(res => {
						if (res.code == 200) {
							val.favorite = !val.favorite;
							uni.showToast({
								title: '操作成功'
							});
						}
					});
			},
			bindChange1(e) {
				// this.value1 = this.list1[e.detail.value[0]];
				this.valueCount = this.list1[e.detail.value[0]];
			},
			bindChange2(e) {
				this.value2 = this.list2[e.detail.value[0]];
			},
			openPop() {
				this.$refs.popup.open();
				this.stop();
			},
			saveSet() {
				this.$refs.popup.close();
				this.cTime = this.value2;
				//this.count = this.value1;
				uni.setStorageSync('cTime', this.value2);
				// uni.setStorageSync('count', this.value1);
				uni.setStorageSync('count', this.valueCount);
				this.num = 0;
				//this.current = this.position - 1;
				this.start();
			},
			closePop() {
				this.$refs.popup.close();
				this.start();
			},
			getSource(index){
				if(index>this.displaySwiperList.length-1){
					index=0;
				}else if(index<0){
					index=this.displaySwiperList.length-1;
				}
				let item = this.displaySwiperList[index];
				if(!item){
					return;
				}
				if(item.source){
					return;
				}
				let that = this;
				this.$http
					.gettts('api/client/word/tts', {
						wordStr: item.name,
						langType:item.languageType===2?"ja":"en"
					}).then((res)=>{
						item.source=res;
					});
			},
			//拼读
			spell(item) {
				console.log('spell=',item)
				if(!item){
					return;
				}
				this.recodePosition();
				return new Promise((resolve,reject)=>{
					if(item?.source?.byteLength){
						const fs = wx.getFileSystemManager();
						const basePath = `${wx.env.USER_DATA_PATH}/audio`;
						const audioPath = `${basePath}/${new Date().getTime()}.mp3`;
						let hasFolder = true;
						try {
							fs.accessSync(basePath);
						} catch (e) {
							hasFolder = false;
						}
						// 没有则先创建audio文件夹
						if (!hasFolder) {
							fs.mkdir({
								dirPath: basePath
							});
						}
						fs.writeFile({
							filePath: audioPath,
							data: item.source,
							encoding: 'binary',
							success: res => {
								console.log('success-play1=',audioPath)
								wxAudio.src = audioPath;
								wxAudio.loop=false;
								wxAudio.autoPlay=false;
								wxAudio.play();
								setTimeout(()=>{
									wxAudio.stop();
									resolve()	
								},1000)
							}
						});
						return;
					}
					let that = this;
					this.$http
						.gettts('api/client/word/tts', {
							wordStr: item.name,
							langType:item.languageType===2?"ja":"en"
						})
						.then(res => {
							item.source=res;
							const fs = wx.getFileSystemManager();
							const basePath = `${wx.env.USER_DATA_PATH}/audio`;
							const audioPath = `${basePath}/${new Date().getTime()}.mp3`;
							let hasFolder = true;
							try {
								fs.accessSync(basePath);
							} catch (e) {
								hasFolder = false;
							}
							// 没有则先创建audio文件夹
							if (!hasFolder) {
								fs.mkdir({
									dirPath: basePath
								});
							}
							fs.writeFile({
								filePath: audioPath,
								data: res,
								encoding: 'binary',
								success: res => {
									console.log('success-play2=',audioPath)
									wxAudio.src = audioPath;
									wxAudio.loop=false;
									wxAudio.autoPlay=false;
									wxAudio.play();
									setTimeout(()=>{
										wxAudio.stop();
										resolve()		
									},1000)
								}
							});
						});
								
				})

			},
			recodePosition() {
				this.$http.put('api/client/word/recordPosition', {
					type: this.type,
					position: this.current
				}, 0, 'application/x-www-form-urlencoded;charset=utf-8').then(res => {});
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #f2f3f8;
	}

	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		font-size: 22rpx;
		color: #333333;
		text-align: center;
		height: 96rpx;
		background: #f9fbff;
		box-shadow: 0rpx 4rpx 8rpx 2rpx rgba(42, 65, 152, 0.05);
		line-height: 96rpx;
		position: fixed;
		z-index: 9;
	}

	.page {
		padding: 116rpx 0 0;
		box-sizing: border-box;
	}

	.content {
		min-height: calc(100vh - 310rpx);
		box-shadow: 0rpx 4rpx 8rpx 2rpx rgba(42, 65, 152, 0.05);
		box-sizing: border-box;
		position: relative;

		.swiper {
			width: 100%;
			height: calc(100vh - 310rpx);

			.swiper-list {
				width: 100%;
				height: calc(100vh - 310rpx);
				padding: 0 30rpx;
				box-sizing: border-box;
			}

			.swiper-item {
				height: 100%;
				padding: 90rpx 30rpx 30rpx;
				background-color: #fff;
				border-radius: 20rpx;
			}
		}

		.collect {
			position: absolute;
			top: 30rpx;
			right: 60rpx;

			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.word {
			font-size: 60rpx;
			font-weight: 800;
			color: #333333;
			text-align: center;
		}

		.spring {
			font-size: 28rpx;
			color: #575a64;
			margin: 20rpx 0 40rpx;
			text-align: center;
		}

		.mean {
			margin-top: 40rpx;
			font-size: 28rpx;
			color: #575a64;
			margin-bottom: 50rpx;
		}

		.memory {
			.label {
				font-size: 28rpx;
				font-weight: bold;
				color: #575a64;
				margin-bottom: 20rpx;
			}

			.con {
				width: 100%;
				background: rgba(84, 128, 248, 0.05);
				border-radius: 10rpx;
				border: 1rpx dashed #5480f8;
				padding: 20rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				font-weight: 400;
				color: #575a64;
				line-height: 1.8;
			}
		}

		.spell {
			margin-top: 100rpx;
			text-align: center;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 50rpx 0;
		}
	}

	.page-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 176rpx;
		padding: 30rpx 32rpx;
		box-sizing: border-box;
		background-color: #fff;
		z-index: 10;

		.set {
			width: 64rpx;
			height: 64rpx;
			margin-right: 30rpx;

			image {
				width: 64rpx;
				height: 64rpx;
			}
		}

		.btn {
			width: 100%;
			height: 90rpx;
			background: #5480f8;
			border-radius: 46rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 32rpx;
			font-weight: 500;
			color: #ffffff;

			&.disable {
				background-color: #cad8fc;
			}
			&.stop {
				background-color: #cad8fc;
			}
		}
	}

	.pop-box {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding-bottom: 50rpx;

		.tit {
			height: 120rpx;
			text-align: center;
			line-height: 120rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
		}

		.picker-view {
			height: 300rpx;

			.item {
				text-align: center;
				line-height: 45px;
				border: none;
				color: #5480f8;
				font-size: 32rpx;
			}
		}

		.save {
			padding-top: 30rpx;
			width: 100%;
			height: 124rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-top: 10rpx solid #f2f3f8;

			.btn {
				margin: 0 auto;
				width: 626rpx;
				height: 90rpx;
				background: #5480f8;
				border-radius: 46rpx;
				text-align: center;
				line-height: 90rpx;
				color: #fff;
				font-size: 32rpx;
				font-weight: bold;
			}
		}
	}
</style>